const NacosConfigClient = require('nacos').NacosConfigClient;
const NacosNamingClient = require('nacos').NacosNamingClient;
const logger = console;


// 初始化配置客户端（已验证正常工作）
const configClient = new NacosConfigClient({
    serverAddr: '127.0.0.1:8848',
    namespace: 'public',
    username: "nacos",
    password: "nacos@123456"
});

// 监听配置变化
async function listenConfig() {
    try {
        await configClient.subscribe({
            dataId: 'default',
            group: 'default',
        }, (content) => {
            console.log('配置更新:', content);
        });

        const content = await configClient.getConfig('default', 'default');
        console.log('当前配置:', content);
    } catch (error) {
        console.error('配置监听错误:', error);
    }
}

// 服务注册和发现
const namingClient = new NacosNamingClient({
    logger,
    serverList: '127.0.0.1:8848', // replace to real nacos serverList
    namespace: 'public',
    username: "nacos",
    password: "nacos@123456"
});
// 服务注册
async function registerService() {
    try {
        await namingClient.ready();
        await namingClient.registerInstance('user-service', {
            ip: '127.0.0.1',
            port: 3000,
        });
        console.log('服务注册成功');
    } catch (error) {
        console.error('服务注册错误:', error);
    }
}

// 服务发现
async function discoverService() {
    try {
        await namingClient.ready();
        const instances = await namingClient.getAllInstances('user-service');
        console.log('可用服务实例:', instances);

        namingClient.subscribe('user-service', (instances) => {
            console.log('服务实例更新:', instances);
        });
    } catch (error) {
        console.error('服务发现错误:', error);
    }
}

// 执行
registerService();
discoverService();


listenConfig();
